/**
 * @author Flower
 * @description Common Storage
 */

import Util from './Util'
let Storage = {
  set(name, obj){
    if( typeof obj === 'object' ){
      localStorage.setItem( name, JSON.stringify(obj) );
    }else{
      localStorage.setItem( name, obj );
    }
  },
  get(name){
    return localStorage.getItem(name)?JSON.parse(localStorage.getItem(name)):'';
  }
}

export const Cart = {
  add(item){
    let cart = Storage.get('cart') || [];
    let isExsit = false;
    cart.map(value=>{
      if( value.id === item.id ){
        isExsit = true;
      }
    })
    if(!isExsit){
      cart.push(item);
      Storage.set('cart',cart);
    }else{
      Util.popup({content:'商品已经在购物车中！'});
    }
  },
  get(){
    return Storage.get('cart') || [];
  },
  isExsit(item){
    let cart = Storage.get('cart') || [];
    let isExsit = false;
    cart.map(value=>{
      if( value.id === item.id ){
        isExsit = true;
      }
    })
    return isExsit;
  },
  delete(item){
    let cart = Storage.get('cart') || [];
    let newCart = [];
    cart.map(value=>{
      if( value.id != item.id ){
        newCart.push(value);
      }
    })
    Storage.set('cart',newCart);

  }
}

